package com.yunying.rispro.config;

import com.yunying.rispro.exception.BusinessException;
import com.yunying.rispro.model.Doctor;
import com.yunying.rispro.service.IRedisService;
import com.yunying.rispro.util.CookieUtils;
import com.yunying.rispro.util.JsonResponseStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IRedisService redisService;

    /**
     * supportsParameter方法返回的true或者false将决定resolveArgument方法执不执行
     * 1）true 执行
     * 2）false 不执行
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return Doctor.class==methodParameter.getParameterType();
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
//       1.将nativeWebRequest转换成HttpServletRequest
        HttpServletRequest req=(HttpServletRequest) nativeWebRequest.getNativeRequest();
//        2.通过request对象获取cookie中的token令牌
        String token = CookieUtils.getCookieValue(req, "token");
//        3.判断token是否为空
        if(token==null){
            throw new BusinessException(JsonResponseStatus.TOKEN_ERROR);
        }
//        4.根据token令牌获取存储在redis中的user对象信息
        Doctor doctor = redisService.getUserByToken(token);
//        5.判断user是否为空
        if(doctor==null){
            throw new BusinessException(JsonResponseStatus.TOKEN_ERROR);
        }
        return doctor;
    }
}
